namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 新增 BOM 明细 处理器
    /// </summary>
    public class BomItemAddHandler : IRequestHandler<BomItemAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BomItem> _bomItemRepo;
        private readonly IBaseRepository<Bom> _bomRepo;
        private readonly ILogger<BomItemAddHandler> _logger;

        public BomItemAddHandler(
            IBaseRepository<BomItem> bomItemRepo,
            IBaseRepository<Bom> bomRepo,
            ILogger<BomItemAddHandler> logger)
        {
            _bomItemRepo = bomItemRepo;
            _bomRepo = bomRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BomItemAddCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.BomId <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM Id 无效", Data = 0 });
                if (request.MaterialId <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "物料Id无效", Data = 0 });
                if (request.Qty <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "用量必须大于0", Data = 0 });

                // 校验BOM存在
                var bom = _bomRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.BomId });
                if (bom == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "关联BOM不存在", Data = 0 });

                // 若有父项，校验父项属于同一BOM
                if (request.ParentId.HasValue)
                {
                    var parent = _bomItemRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.ParentId.Value });
                    if (parent == null || parent.BomId != request.BomId)
                        return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "父项不存在或不属于该BOM", Data = 0 });
                }

                var entity = new BomItem
                {
                    BomId = request.BomId,
                    BomName = bom.Name,
                    ParentId = request.ParentId,
                    MaterialId = request.MaterialId,
                    MaterialName = request.MaterialName,
                    Qty = request.Qty,
                    Position = request.Position
                };
                if (!string.IsNullOrWhiteSpace(request.CreateUser))
                {
                    entity.CreateUser = request.CreateUser!;
                }

                var newId = _bomItemRepo.Create(entity);
                result.Code = newId > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = newId > 0 ? "新增BOM明细成功" : "新增BOM明细失败";
                result.Data = newId;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("新增BOM明细被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "新增BOM明细异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "新增BOM明细异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
